﻿using B.S.DataBase.MyProject.ErrorCode;
using B.S.Traceability.Domain;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Read.API.Applicantion.Command.BreedCommand;
using MediatR;

namespace B.S.Traceability.Read.API.Applicantion.CommandHandler.BreedCommandHandler
{
    public class QueryBreedCommandHandler : IRequestHandler<QueryBreedCommand, APIResult<List<SU_BreedInfo>>>
    {
        private readonly IBaseRepository<SU_BreedInfo> breedRep;
        public QueryBreedCommandHandler(IBaseRepository<SU_BreedInfo> breedRep)
        {
            this.breedRep = breedRep;
        }
        public Task<APIResult<List<SU_BreedInfo>>> Handle(QueryBreedCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<SU_BreedInfo>> result = new APIResult<List<SU_BreedInfo>>();
            var firstItem = breedRep.GetAll().Result
                .Where(x => x.ProductionCode == request.ProductionCode)
                .OrderByDescending(x => x.BreedId)
                .FirstOrDefault();

            if (firstItem != null)
            {
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
                result.data = new List<SU_BreedInfo> { firstItem };
            }
            else
            {
                result.Code = APIEnum.查询失败; 
                result.Msg = APIEnum.查询失败.ToString();
                result.data = new List<SU_BreedInfo>();
            }
            return Task.FromResult(result);
        }
    }
}
